<?php

class EmploymentContractForm extends BaseForm
{

    private $employeeService;
    private $employmentContractService;
    private $employmentContractTypeService;
    private $employee;
    private $employmentContractTypes;

    public $employmentContractId;

    /**
     * Get EmployeeService
     * @returns EmployeeService
     */
    public function getEmployeeService()
    {
        if (is_null($this->employeeService)) {
            $this->employeeService = new EmployeeService();
            $this->employeeService->setEmployeeDao(new EmployeeDao());
        }
        return $this->employeeService;
    }

    /**
     * Set EmployeeService
     * @param EmployeeService $employeeService
     */
    public function setEmployeeService(EmployeeService $employeeService)
    {
        $this->employeeService = $employeeService;
    }

    public function getEmploymentContractService()
    {
        if (is_null($this->employmentContractService)) {
            $this->employmentContractService = new EmploymentContractService();
            $this->employmentContractService->setEmploymentContractDao(new EmploymentContractDao());
        }
        return $this->employmentContractService;
    }

    public function getEmploymentContractTypeService()
    {
        if (is_null($this->employmentContractTypeService)) {
            $this->employmentContractTypeService = new EmploymentContractTypeService();
            $this->employmentContractTypeService->setEmploymentContractTypeDao(new EmploymentContractTypeDao());
        }
        return $this->employmentContractTypeService;
    }

    public function configure()
    {
        $this->employmentContractPermissions = $this->getOption('employmentContractPermissions');

        $empNumber = $this->getOption('empNumber');
        $this->employee = $this->getEmployeeService()->getEmployee($empNumber);

        $this->employmentContractId = $this->getOption('employmentContractId');

        $employmentContract = false;
        if (!empty($this->employmentContractId)) {
//            $employmentContract = Doctrine::getTable('EmploymentContract')->find($this->employmentContractId);
            $employmentContract = $this->getEmploymentContractService()->getEmploymentContractById($this->employmentContractId);
            if ($employmentContract == false) {
                throw new PIMServiceException('Invalid Employment Contract');
            }
        }
        $this->employmentContractTypes = $this->_getEmploymentContractTypes(($employmentContract === false) ? 0 : $employmentContract->employment_contract_type_id);

        $widgets = array('empNumber' => new sfWidgetFormInputHidden(array(), array('value' => $this->employee->empNumber)));
        $validators = array('empNumber' => new sfValidatorString(array('required' => true)));

        if ($this->employmentContractPermissions->canRead()) {

            $employmentContractWidgets = $this->getEmploymentContractWidgets();
            $employmentContractValidators = $this->getEmploymentContractValidators();

            if (!($this->employmentContractPermissions->canUpdate() || $this->employmentContractPermissions->canCreate())) {
                foreach ($employmentContractWidgets as $widgetName => $widget) {
                    $widget->setAttribute('disabled', 'disabled');
                }
            }
            $widgets = array_merge($widgets, $employmentContractWidgets);
            $validators = array_merge($validators, $employmentContractValidators);
        }

        $this->setWidgets($widgets);
        $this->setValidators($validators);

        $this->widgetSchema->setNameFormat('employmentContract[%s]');

        $this->validatorSchema->setPostValidator(
            new sfValidatorSchemaCompare('start_date', sfValidatorSchemaCompare::LESS_THAN, 'end_date',
                array(),
                array('invalid' => 'The start date must be before the end date')
            )
        );

        if (!empty($this->employmentContractId)) {
            $this->setDefault('empContractNo', $employmentContract->empContractNo);
            $this->setDefault('employment_contract_type', $employmentContract->employment_contract_type_id);
            $this->setDefault('duration', $employmentContract->duration);
            $this->setDefault('salary', $employmentContract->salary);
            $this->setDefault('start_date', set_datepicker_date_format($employmentContract->start_date));
            $this->setDefault('end_date', set_datepicker_date_format($employmentContract->end_date));
            $this->setDefault('comment', $employmentContract->comment);
        }
    }


    /*
     * Tis fuction will return the widgets of the form
     */
    public function getEmploymentContractWidgets()
    {
        $widgets = array();

        $widgets['empContractNo'] = new sfWidgetFormInputText();
        $widgets['employment_contract_type'] = new sfWidgetFormSelect(array('choices' => $this->employmentContractTypes));
        $widgets['duration'] = new sfWidgetFormInputText();
        $widgets['salary'] = new sfWidgetFormInputText();
        $widgets['start_date'] = new ohrmWidgetDatePicker(array(), array('id' => 'start_date'));
        $widgets['end_date'] = new ohrmWidgetDatePicker(array(), array('id' => 'end_date'));
        $widgets['comment'] = new sfWidgetFormTextArea();

        return $widgets;
    }


    /*
     * Tis fuction will return the form validators
     */
    public function getEmploymentContractValidators()
    {
        $inputDatePattern = sfContext::getInstance()->getUser()->getDateFormat();

        $validators = array(
            'empContractNo' => new sfValidatorString(array('required' => true, 'trim' => true, 'max_length' => 10)),
            'employment_contract_type' => new sfValidatorChoice(array('choices' => array_keys($this->employmentContractTypes))),
            'duration' => new sfValidatorString(array('required' => false, 'max_length' => 30)),
            'salary' => new sfValidatorNumber(array('required' => true, 'trim' => true, 'min' => 0, 'max' => 999999999.99)),
            'start_date' => new ohrmDateValidator(array('date_format' => $inputDatePattern, 'required' => false),
                    array('invalid' => 'Date format should be ' . $inputDatePattern)),
            'end_date' => new ohrmDateValidator(array('date_format' => $inputDatePattern, 'required' => false),
                    array('invalid' => 'Date format should be ' . $inputDatePattern)),
            'comment' => new sfValidatorString(array('required' => false, 'max_length' => 255)),
        );

        return $validators;
    }

    /**
     * Save employee contract
     */
    public function save()
    {
        $resultArray = array();

        $empNumber = $this->getValue('empNumber');

        $employmentContract = false;

        if (!empty($this->employmentContractId)) {
//            $employmentContract = Doctrine::getTable('EmploymentContract')->find($this->employmentContractId);
            $employmentContract = $this->getEmploymentContractService()->getEmploymentContractById($this->employmentContractId);
            if ($employmentContract == false) {
                throw new PIMServiceException('Invalid Employment Contract');
            }

            $resultArray['messageType'] = 'employmentcontract.success';
            $resultArray['message'] = __(TopLevelMessages::UPDATE_SUCCESS);
        }

        if ($employmentContract === false) {
            $employmentContract = new EmploymentContract();
            $employmentContract->emp_number = $empNumber;

            $resultArray['messageType'] = 'employmentcontract.success';
            $resultArray['message'] = __(TopLevelMessages::SAVE_SUCCESS);
        }

        $employmentContract->empContractNo = $this->getValue('empContractNo');
        $employmentContract->employment_contract_type_id = $this->getValue('employment_contract_type');
        $employmentContract->duration = $this->getValue('duration');
        $employmentContract->salary = $this->getValue('salary');
        $employmentContract->start_date = $this->getValue('start_date');
        $employmentContract->end_date = $this->getValue('end_date');
        $employmentContract->comment = $this->getValue('comment');

        $employmentContract->save();

        return $resultArray;
    }

    private function _getEmploymentContractTypes($employmentContractTypeId)
    {

        $employmentContractTypeList = $this->getEmploymentContractTypeService()->getEmploymentContractTypeList("", "", false);
        $choices = array('' => '-- ' . __('Select') . ' --');

        foreach ($employmentContractTypeList as $employmentContractType) {
            if (($employmentContractType->getIsDeleted() == EmploymentContractType::ACTIVE) || ($employmentContractType->getId() == $employmentContractTypeId)) {
                $code = ($employmentContractType->getIsDeleted() == EmploymentContractType::DELETED) ? $employmentContractType->getCode() . " (" . __("Deleted") . ")" : $employmentContractType->getCode();
                $choices[$employmentContractType->getId()] = $code;
            }
        }
        return $choices;
    }
}

